import { useCallback, useEffect, useState } from "react";
import GanttContext from "../context";
import type { FlattenedTask, TaskMode, TaskProps } from "../types";
import type { Dayjs } from "dayjs";
import { flattenTasks, getInitialExpandedTasks } from "../helpers/utils";
import { GanttConsts } from "../constants";

interface GanttProviderProps {
  children: React.ReactNode;
  tasksList: TaskProps[];
  tasksStart: Dayjs;
  tasksEnd: Dayjs;
  containerWidth: number;
  containerHeight: number;
  hideTaskTable: boolean;
  setHideTaskTable: (hideTaskTable: boolean) => void;
}

export default function GanttProvider(props: GanttProviderProps) {
  const {
    children,
    tasksList,
    tasksStart,
    tasksEnd,
    containerHeight,
    containerWidth,
    hideTaskTable,
    setHideTaskTable,
  } = props;
  const [tasks, setTasks] = useState<TaskProps[]>(tasksList);
  const [taskMode, setTaskMode] = useState<TaskMode>("Day");
  const [ganttWidth, setGanttWidth] = useState(0);
  const [ganttHeight, setGanttHeight] = useState(0);
  const [scrollTop, setScrollTop] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);

  const [flattenedTasks, setFlattenedTasks] = useState<FlattenedTask[]>([]);
  const [expandedTasks, setExpandedTasks] = useState<Set<string>>(new Set());

  useEffect(() => {
    const initialExpanded = getInitialExpandedTasks(tasksList);
    setExpandedTasks(initialExpanded);
  }, [tasksList]);

  useEffect(() => {
    const flattened = flattenTasks(tasksList, expandedTasks);
    setFlattenedTasks(flattened);
    setGanttHeight(flattened.length * GanttConsts.ITEM_HEIGHT);
  }, [tasksList, expandedTasks]);

  // 切换展开/折叠状态
  const toggleExpand = useCallback((taskId: string) => {
    setExpandedTasks((prev) => {
      const newExpanded = new Set(prev);
      if (newExpanded.has(taskId)) {
        newExpanded.delete(taskId);
      } else {
        newExpanded.add(taskId);
      }
      return newExpanded;
    });
  }, []);

  return (
    <GanttContext.Provider
      value={{
        tasks,
        setTasks,
        tasksStart,
        tasksEnd,
        taskMode,
        setTaskMode,
        hideTaskTable,
        setHideTaskTable,
        containerHeight,
        containerWidth,
        ganttWidth,
        setGanttWidth,
        ganttHeight,
        setGanttHeight,
        scrollTop,
        setScrollTop,
        scrollLeft,
        setScrollLeft,
        flattenedTasks,
        setFlattenedTasks,
        expandedTasks,
        setExpandedTasks,
        toggleExpand,
      }}
    >
      {children}
    </GanttContext.Provider>
  );
}
